package com.ruoyi.feike.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.InstanceIdUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.mapper.BasicInformationMapper;
import com.ruoyi.feike.mapper.NotesMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IFileuploadService;
import com.ruoyi.feike.service.ITierCashDepositService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * feikeController
 *
 * @author ruoyi
 * @date 2022-08-02
 *
 * 二网
 */
@RestController
@RequestMapping("/feike/deposit")
public class TierCashDepositController extends BaseController
{
    @Autowired
    private ITierCashDepositService tierCashDepositService;

    @Autowired
    private IFileuploadService fileuploadService;

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;
    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TierCashDeposit tierCashDeposit)
    {
        startPage();
        List<TierCashDeposit> list = tierCashDepositService.selectTierCashDepositList(tierCashDeposit);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(AnnualReviewy annualReviewy, TierCashDeposit tierCashDeposit)
    {
        startPage();
        List<AnnualReviewyHistoryVO> list = tierCashDepositService.selectTierCashDepositListAll(annualReviewy,tierCashDeposit);
        return getDataTable(list);
    }

    /**
     * 导出feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:export')")
    @Log(title = "feike", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TierCashDeposit tierCashDeposit)
    {
        List<TierCashDeposit> list = tierCashDepositService.selectTierCashDepositList(tierCashDeposit);
        ExcelUtil<TierCashDeposit> util = new ExcelUtil<TierCashDeposit>(TierCashDeposit.class);
        return util.exportExcel(list, "deposit");
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(tierCashDepositService.selectTierCashDepositById(id));
    }

    /**
     * 获取feike详细信息
     */
    @GetMapping(value = "/ByInstanceId/{instanceId}")
    public AjaxResult getInfoByInstanceId(@PathVariable("instanceId") String instanceId)
    {
        return AjaxResult.success(tierCashDepositService.selectTierCashDepositByInstanceId(instanceId));
    }

    /**
     * 根据dealer获取详细信息
     */
    @PostMapping(value = "/getInfoByDealer")
    public AjaxResult getInfoByDealer(@RequestParam String dralerName)
    {
        return AjaxResult.success(tierCashDepositService.selectTierCashDepositByDralerName(dralerName));
    }

    /**
     * 获取所有列表数据
     */
    @PostMapping(value = "/getInfoList")
    public AjaxResult getInfoList(@RequestBody Map<String,Object> map)
    {
        return AjaxResult.success(tierCashDepositService.selectTierCashDepositLists((String)map.get("dralerName")));
    }

    @PostMapping(value = "/getTowndTierCashDeposit")
    public AjaxResult getTowndTierCashDeposit(@RequestBody Map<String,Object> map)
    {
        return AjaxResult.success(tierCashDepositService.getTowndTierCashDeposit((String)map.get("dealerCode")));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String,Object> map)
    {
        System.out.println("tierCashDeposit的map对象=="+map);
        String currentVal = instanceIdUtil.getRedisInstanceId("2T");
        String instanceId = instanceIdUtil.getIstanceId("2T", currentVal);
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        System.out.println(ip);

        Notes notes1 = new Notes();
        notes1.setComments((String)map.get("comments"));
        notes1.setId(IdUtils.simpleUUID());
        notes1.setInstanceId(instanceId);
        notesMapper.insertNotes(notes1);
        //String instanceId = IdUtils.get16UUID();
        TierCashDeposit tierCashDeposit =new TierCashDeposit();
        StringBuilder parkinglocationObj = new StringBuilder();
        Object parkinglocations = map.get("parkinglocations");
        if (parkinglocations!=null){
            List parkinglocationList = (List) parkinglocations;//数组
            if (parkinglocationList!=null && parkinglocationList.size()>0){
                for (int i = 0; i < parkinglocationList.size(); i++) {
                    parkinglocationObj.append(parkinglocationList.get(i));
                    parkinglocationObj.append(",");
                }
            }
        }

        if (!StringUtils.isEmpty(parkinglocationObj)){
            parkinglocationObj.deleteCharAt(parkinglocationObj.length()-1);
            tierCashDeposit.setParkinglocations(parkinglocationObj.toString());
        }
        Object parkinglocation = map.get("parkingLocation");
        if(parkinglocation!=null){
            tierCashDeposit.setParkingLocation(map.get("parkingLocation").toString());
        }

        //TODO 数据待校验
        Object permitted2ndTierWithoutDesposit = map.get("permitted2ndTierWithoutDesposit");
        Object permitted2ndTierWithDesposit = map.get("permitted2ndTierWithDesposit");
        Object registeredTwoTierNumber = map.get("registeredTwoTierNumber");
        Object twoTierWithDesposit = map.get("twoTierWithDesposit");
        Object ndTierCashDeposit = map.get("ndTierCashDeposit");
        Object twondTierDeposit = map.get("twondTierDeposit");
        if(permitted2ndTierWithoutDesposit!=null){
            tierCashDeposit.setPermitted2ndTierWithoutDesposit(Long.valueOf(String.valueOf(permitted2ndTierWithoutDesposit)));
        }
        if(permitted2ndTierWithDesposit!=null){
            tierCashDeposit.setPermitted2ndTierWithDesposit(Long.valueOf(String.valueOf(permitted2ndTierWithDesposit)));
        }

        if(registeredTwoTierNumber!=null){
            tierCashDeposit.setRegisteredTwoTierNumber(new BigDecimal(registeredTwoTierNumber.toString()));
        }

        if(twoTierWithDesposit!=null){
            tierCashDeposit.setTwoTierWithDesposit(new BigDecimal(twoTierWithDesposit.toString()));
        }
        if(ndTierCashDeposit!=null){
            tierCashDeposit.setTowndTierCashDeposit(new BigDecimal(ndTierCashDeposit.toString()));
        }
        if(twondTierDeposit!=null){
            tierCashDeposit.setTwondTierDeposit(new BigDecimal(twondTierDeposit.toString()));
        }
        Object dearler = map.get("dearler");
        if(dearler!=null){
            tierCashDeposit.setDearler(map.get("dearler").toString());
            tierCashDeposit.setDealerNameCn(map.get("dearler").toString());
        }
        if(ObjectUtil.isNotNull(map.get("reason"))){
            tierCashDeposit.setReason(map.get("reason").toString());
        }
        if(ObjectUtil.isNotNull(map.get("refundType"))){
            tierCashDeposit.setRefundType(map.get("refundType").toString());
        }
        if(ObjectUtil.isNotNull(map.get("parkingLocation"))){
            tierCashDeposit.setParkingLocation(map.get("parkingLocation").toString());
        }
        Object groupName = map.get("groupName");
        BasicInformation basicInformationNew = new BasicInformation();
        if(groupName!=null){
            tierCashDeposit.setGroupNameCn(map.get("groupName").toString());
            basicInformationNew.setGroupNameEN(map.get("groupName").toString());
        }
        basicInformationNew.setInstanceId(instanceId);
        basicInformationNew.setId(IdUtils.simpleUUID());
        basicInformationNew.setDealerNameCN(map.get("dearler").toString());
        basicInformationMapper.insertBasicInformation(basicInformationNew);

        Object dealerCode = map.get("dealerCode");
        if(dealerCode!=null){
            tierCashDeposit.setDealerCode(map.get("dealerCode").toString());
        }
        Object units = map.get("units");
        if(units!=null){
            tierCashDeposit.setUnits(map.get("units").toString());
        }
        Object dailyBankFeedback = map.get("dailyBankFeedback");
        if(dailyBankFeedback!=null){
            tierCashDeposit.setDailyBankFeedback(map.get("dailyBankFeedback").toString());
        }
        Object notes = map.get("notes");
        if(notes!=null){
            tierCashDeposit.setNotes(map.get("notes").toString());
        }
        Object tierDepositReceivable = map.get("tierDepositReceivable");
        if(tierDepositReceivable!=null){
            tierCashDeposit.setTierDepositReceivable(Long.valueOf(map.get("tierDepositReceivable").toString()));
        }
        Object tierDepositGap = map.get("tierDepositGap");
        if(tierDepositGap!=null){
            tierCashDeposit.setTierDepositGap(Long.valueOf(map.get("tierDepositGap").toString()));
        }
        Object fileList =  map.get("depositFileList");
        if(fileList!=null){
            List<Fileupload> fileupload= (List<Fileupload>) fileList;
            tierCashDeposit.setDepositFileList(fileupload);
        }
        System.out.println("tierCashDeposit新增对象=="+tierCashDeposit);

        List<Fileupload> depositFileList = tierCashDeposit.getDepositFileList();
        String s = JSON.toJSONString(depositFileList);
        depositFileList = JSON.parseArray(s, Fileupload.class);
        System.out.println("tierCashDeposit上传文件的内容： "+depositFileList);
        if (depositFileList!=null&&depositFileList.size()>0){
            for (Fileupload fileuploadVO : depositFileList) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.getFileName());
                fileupload.setOriginalFileName(fileuploadVO.getOriginalFileName());
                fileupload.setUrl(fileuploadVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("tierCashDeposit");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }
        return toAjax(tierCashDepositService.insertTierCashDeposit(tierCashDeposit,instanceId,map.get("caoGao")+""));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TierCashDeposit tierCashDeposit,@RequestBody Map<String,Object> map)
    {
        System.out.println("TierCashDeposit修改=="+map);
        //2网op文件上传
        Object fileList =  map.get("opFileList");
        if(fileList!=null){
            List<Fileupload> fileuploads = (List<Fileupload>) fileList;
            String s = JSON.toJSONString(fileuploads);
            fileuploads = JSON.parseArray(s, Fileupload.class);
            for (Fileupload fileupload : fileuploads) {
                if(StringUtils.isEmpty(fileupload.getId())){
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(tierCashDeposit.getInstanceId());
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                //fileupload.setOriginalFileName(fileupload.getName());
                fileupload.setType("opFileList");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","上传文件","File Upload",tierCashDeposit.getInstanceId(),null,fileupload,null);

                }
            }
        }
        Object depositFileList =  map.get("depositFileList");
        if(depositFileList!=null){
            List<Fileupload> depositFileuploads = (List<Fileupload>) depositFileList;
            String s = JSON.toJSONString(depositFileuploads);
            depositFileuploads = JSON.parseArray(s, Fileupload.class);
            for (Fileupload fileupload : depositFileuploads) {
                if(StringUtils.isEmpty(fileupload.getId())){
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(tierCashDeposit.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("tierCashDeposit");
                    fileuploadService.insertFileupload(fileupload);
                    annualReviewyService.saveDbLog("1","上传文件","File Upload",tierCashDeposit.getInstanceId(),null,fileupload,null);
                }
            }
        }

        return toAjax(tierCashDepositService.updateTierCashDeposit(tierCashDeposit,map));
    }

    /**
     * 删除feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:deposit:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tierCashDepositService.deleteTierCashDepositByIds(ids));
    }

}
